<?php

namespace App\Http\Middleware;

use App\Exceptions\Customize\ParamsException;
use Closure;

class ApiCheckSign {
    /**
     *
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        //测试环境
        if(config("app.debug"))
        {
            return $next($request);
        }

        $sign = request()->m;
        $type = request()->header('Device-Type');
        $json = file_get_contents('php://input');
//        var_dump($json);die;
//        echo $json;die;
        if(request()->n == 'UploadImage') return $next($request);
//        dd(md5('chxgo%fskfsd@h.cfvkxn'));
        if(!$sign){
            throw new ParamsException([
                'error_code' => 10003,
                'message' => '缺少签名信息'
            ]);
        }
        
        if($type == 'h5'){
            $sign_key = config('global.h5_sign_key');
        }
        else{
            $sign_key = config('global.app_sign_key');
        }

        $object = json_decode($json);

        unset($object->m);
        $json_params = json_encode($object, JSON_UNESCAPED_UNICODE);
//        echo md5($json_params.$sign_key);die;
        if($sign != md5($json_params.$sign_key)){
            throw new ParamsException([
                'error_code' => 10004,
                'message' => '签名错误'
            ]);
        }
        request()->m = $sign;
        return $next($request);
    }
    
}
